import type { ProgramAvailable } from '@/api/appliance'
import type { Option, ValueType } from '../components/parameterCard.vue'
import { WASHER_SPINSPEED_KEY } from '@/constants/Command'
import type { BaseController } from '@/controller/BaseAppliance/definition'

export function generalUnitFormatter(
  key: string,
  value: string | number | boolean | null | undefined,
  unit: string | undefined
): string {
  if (unit) return unit

  switch (key) {
    case WASHER_SPINSPEED_KEY: {
      return 'rpm'
    }
    default: {
      return ''
    }
  }
}

export function getNumberOptions(option: ProgramAvailable.NumberOption): Option[] {
  const { min, max } = option.constraints

  const step = option.constraints.stepsize || 1 // 步进
  const selectOptions: Option[] = []

  // 如果时间调节范围是60s或者600s，改步长s为min
  let stepLabel = option.constraints.stepsize || 1
  let minLabel = min
  if (option.unit === 'seconds' && option.constraints.stepsize && option.constraints.stepsize % 60 === 0) {
    stepLabel = option.constraints.stepsize / 60
    minLabel = min / 60
  }
  for (let i = 0; min + i * step <= max; i++) {
    const stepValue = min + i * step
    const labelValue = minLabel + i * stepLabel
    selectOptions.push({
      label: String(labelValue),
      value: stepValue,
      key: option.key,
    })
  }
  return selectOptions
}

export function getEnumOptions(option: ProgramAvailable.EnumOption): Option[] {
  const { allowedvalues, displayvalues } = option.constraints
  return allowedvalues.map((value, index) => ({
    label: displayvalues[index],
    value,
    key: option.key,
  }))
}

/**
 * Demo mode 方法
 */

export function setVirtualOptionValue(control: BaseController.Control, key: string, value: ValueType) {
  const demoDetail = control.store._datasource.detail
  if (!demoDetail || !Array.isArray(demoDetail.option)) return

  const demoOption = demoDetail.option.find((option) => option.key === key)
  if (!demoOption) return

  // 赋值value
  demoOption.value = value

  try {
    // 非boolean 回填displayvalue
    if (typeof value !== 'boolean') {
      const availableOptions = control.store.availableParameter?.options || []
      const availableOption = availableOptions?.find((available) => available.key === key)
      const availableConstraints = (availableOption as ProgramAvailable.EnumOption)?.constraints
      // 判断是否为枚举值
      if (availableConstraints?.allowedvalues) {
        const matchedIndex = availableConstraints.allowedvalues.findIndex((allowedvalue) => allowedvalue === value)
        if (matchedIndex === -1) throw new Error('Available option does not exist for value: ' + value)
        demoOption.displayvalue = availableConstraints.displayvalues[matchedIndex]
      }
    }
  } catch (e) {
    console.error(e)
  }
}
